
package sbc.jms;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xvsm.api.core.Capi;
import org.xvsm.api.core.CapiFactory;
import org.xvsm.api.core.ContainerRef;
import org.xvsm.api.core.CoordinationTypes;
import org.xvsm.api.core.Entry;
import org.xvsm.api.core.Tuple;
import org.xvsm.api.core.ValueTypes;
import org.xvsm.client.ClientCapi;
import sbc.fabrik.model.Employee;
import sbc.fabrik.model.Platine;
import sbc.util.Util;

/**
 *
 * @author goran
 */
public class Logistic extends Employee {
    
    QueueConnectionFactory  queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
    
    private Capi capi;
    private ContainerRef cref;
    
    public Logistic(int id) {
        this(id, null);
    }
    
    public Logistic(int id, String url) {
        super(id);
        Context jndiContext = null;
        
        // xvsm
            if (url == null) {
                System.out.println("using embeded xvsm core");
                capi = CapiFactory.createCapi();
            } else {
                capi = new ClientCapi(url);
            }
  
        
        //          cref = capi.createContainer(CoordinationTypes.FIFO);
        try {
            
            capi.init(false);
            cref = Util.getOrCreateNamedContainer(capi, "DefaultContainer", CoordinationTypes.FIFO);
            
            Properties properties = new Properties();
            properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
            properties.put(Context.PROVIDER_URL, "localhost");
            
            jndiContext = new InitialContext(properties);
            
            queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("ConnectionFactory");
            queue = (Queue) jndiContext.lookup("queue/sbc");
            
        } catch (NamingException e) {System.out.println("JNDI lookup failed: " + e.toString());
        e.printStackTrace();
        System.exit(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    
    
    public void work() {
        try {
            ObjectMessage message = null;
            
            queueConnection = queueConnectionFactory.createQueueConnection();
            QueueSession session = (QueueSession)  queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            String query = "ModulType = '" + Platine.class.getCanonicalName() + "'"
                    + "AND Completed = true";
            //System.out.println(query);
            QueueReceiver subscriber =  session.createReceiver(queue, query);
            
            queueConnection.start();
            System.out.println("receiving...");
            
            
            ObjectMessage modul =  (ObjectMessage) subscriber.receive();
            Platine platine = (Platine) modul.getObject();
            
            System.out.println("LOG: " + platine.toString());
            // write back to mozartspace!
            // BOARD -> UNIT is ready
            
            Entry a0 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, "UNIT");
            Entry a1 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, platine.getPid());
            Tuple t1 = new Tuple();
            t1.addEntry(a0);
            t1.addEntry(a1);
            List<Entry> entries = new LinkedList<Entry>();
            entries.add(t1);
            
            // Write the list of Entries into the created container.
            capi.write(cref, entries);
            
            
            
            
            
            
            System.out.println("**************************************************");
            
            
            
        } catch (Exception e) {
            System.out.println("Exception occurred: " +
                    e.toString());
            e.printStackTrace();
        } finally {
            if (queueConnection != null) {
                try {
                    queueConnection.close();
                } catch (JMSException e) {}
            }
        }
        
    }
    
    public static void main(String[] args) {
            Logger.getLogger("org.xvsm.client").setLevel(Level.FATAL);

        
        
        
        InputStreamReader       inputStreamReader = null;
        char                    answer = '\0';
        
        Logistic logWorker = new Logistic(Integer.parseInt(args[0]), args[1]);
        
        System.out.println("To end program, enter Q or q, then <return>");
        inputStreamReader = new InputStreamReader(System.in);
        while (!((answer == 'q') || (answer == 'Q'))) {
            
            logWorker.work();
            
        }
        try {
            answer = (char) inputStreamReader.read();
        } catch (IOException e) {
            System.out.println("I/O exception: "
                    + e.toString());
        }
        
    }
    
    
    
}
